<!--
 * @Autor: Ruohong Yu
 * @Date: 2021-11-27 16:40:05
 * @LastEditors: Haiting Zhao
 * @LastEditTime: 2021-12-19 13:11:13
 * @Description: 角色管理
 * @FilePath: \Management-of-Scientific-Research-in-Universities-Front\src\views\systemmanage\Role.vue
-->

<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-bottom:10px">
      <el-breadcrumb-item :to="{ name:'WorkPlace' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>管理角色</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button icon="el-icon-plus" type="primary" style="margin-bottom:10px" @click="AddRoleDialogVisible = true">
            添加角色
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="rolesList.slice((queryInfo.pagenum-1)*queryInfo.pagesize,queryInfo.pagenum*queryInfo.pagesize)" border stripe>
        <el-table-column type="index" label="#" />
        <el-table-column label="角色名称" prop="roleName" />
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.roleId)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.roleId)"
            >删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row.roleId)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        style="text-align: right;"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totle"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="60%"
      @close="setRightDialogClosed"
    >
      <el-row :gutter="10">
        <el-col :span="2" />
        <el-col :span="8">
          <el-tree
            v-if="isShowTree"
            ref="treeRef"
            :data="rightsList"
            :props="treeProps"
            show-checkbox
            node-key="permissionId"
            :default-checked-keys="defKeys"
            :default-expanded-keys="defKeys"
          />
        </el-col>
        <!-- 右侧Tag显示权限 -->
        <el-col :span="14">
          <div v-if="f" class="bdtop" />
          <el-row v-for="item in rightsList" :key="item.permissionId" :class="[isShowTag(item.permissionId)?'bdbottom':'', isShowTag(item.permissionId)?'vcenter':'']">
            <el-col :span="5">
              <el-tag v-if="isShowTag(item.permissionId)">{{ item.permissionName }}</el-tag>
              <i v-if="isShowTag(item.permissionId)" class="el-icon-caret-right" />
            </el-col>
            <el-col :span="19">
              <el-row v-for="item2 in item.sonPermissions" :key="item2.permissionId" class="vcenter">
                <el-col :span="6">
                  <el-tag v-if="isShowTag(item2.permissionId)" type="success">{{ item2.permissionName }}</el-tag>
                  <i v-if="isShowTag(item2.permissionId)" class="el-icon-caret-right" />
                </el-col>
                <el-row v-for="(item3) in item2.sonPermissions" :key="item3.permissionId">
                  <el-col :span="18">
                    <el-tag v-if="isShowTag(item3.permissionId)" closable type="warning" @close="deletePermissionById(item3.permissionId)">{{ item3.permissionName }}</el-tag>
                  </el-col>
                </el-row>
              </el-row>
            </el-col>
          </el-row>
          <!-- <button @click="de">取消</button> -->
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogClosed">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="AddRoleDialogVisible"
      width="40%"
      @close="addRoleDialogClosed"
    >
      <el-form
        ref="addRoleFormRef"
        :model="addRoleForm"
        :rules="addRoleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRoleDialogVisible"
      width="40%"
      @close="editRoleDialogClosed"
    >
      <el-form
        ref="editRoleFormRef"
        :model="editRoleForm"
        :rules="editRoleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="删除角色"
      :visible.sync="deleteRoleDialogVisible"
      width="40%"
      @close="deleteRoleDialogClosed"
    >
      <el-form
        label-width="100px"
      >
        确认删除此角色？
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'Role',
  data() {
    return {
      // 获取用户列表查询参数对象
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 每页显示多少数据
        pagesize: 5
      },
      // 所有角色列表
      rolesList: [
      ],
      // 分配权限框
      setRightDialogVisible: false,
      // 权限列表
      rightsList: [],
      //  树形控件的属性绑定对象
      treeProps: {
        label: 'permissionName',
        children: 'sonPermissions'
      },
      //   默认选中节点ID值
      defKeys: [],
      //   添加用户对话框
      AddRoleDialogVisible: false,
      // 添加角色表单
      addRoleForm: {},
      //   添加角色表单验证
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      //   编辑角色信息
      editRoleForm: {},
      editRoleDialogVisible: false,
      editRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 删除用户
      deleteRoleDialogVisible: false,
      roleId: '',
      allList: [],
      deletePermissionId: -1,
      isShowTree: false,
      // tag展示权限的id
      tagList: [],
      f: 0,
      totle: 0
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    /**
     * @description: 判断标签是否出现
     * @param {*}
     * @return {*}
     * @author: Hongting Yuan
     */
    isShowTag(Pid) {
      if (this.tagList.indexOf(Pid) > -1) {
        this.f = 1
      }
      return this.tagList.indexOf(Pid) > -1
    },
    // 监听 pagesize改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagenum = newSize
      this.getUserList()
    },
    /**
     * @description: 获取tag展示权限的id List
     * @param {*}
     * @return {*}
     * @author: Hongting Yuan
     */
    getTagList() {
      // console.log('getTagList')
      if (this.rightsList) {
        for (var i = 0; i < this.rightsList.length; i++) {
          // 一级
          var arr1 = this.rightsList[i]
          if (arr1.sonPermissions) {
            for (var j = 0; j < arr1.sonPermissions.length; j++) {
            // 二级
              var arr2 = arr1.sonPermissions[j].sonPermissions
              if (arr2) {
                for (var k = 0; k < arr2.length; k++) {
                  var id = arr2[k].permissionId
                  if (this.defKeys.indexOf(id) > -1) {
                  // 加入子权限id
                    if (this.tagList.indexOf(arr1.sonPermissions[j].permissionId) <= -1) {
                      this.tagList.push(arr1.sonPermissions[j].permissionId)
                    }
                    // 加入二级权限id
                    if (this.tagList.indexOf(arr1.permissionId) <= -1) {
                      this.tagList.push(arr1.permissionId)
                    }
                    // 加入一级权限id
                    if (this.tagList.indexOf(id) <= -1) {
                      this.tagList.push(id)
                    }
                  }
                }
              }
            }
          }
        }
        // console.log('this.tagList', this.tagList)
      }
    },
    /**
     * @description: tag删除子标签，el-tree同步删除
     * @param {*} Pid
     * @return {*}
     * @author: Hongting Yuan
     */
    deletePermissionById(Pid) {
      var dellist = []
      dellist[0] = { permissionId: Pid, roleId: this.roleId }
      axios.post('/rolePer/deletePermission', {
        list: dellist
      })
        .then(() => {
          this.deleteRights(Pid)
          this.defKeys = []
          this.allList = []
          this.getRolesList()
          this.showSetRightDialog(this.roleId)
          this.$message.success('成功删除子权限')
        })
        .catch((err) => {
          this.$message.info(err.msg)
        })
    },

    /**
     * @description: 角色树展示对应按钮删除权限
     * @param {*} Pid
     * @return {*}
     * @author: Ruohong Yu
     */
    deleteRights(Pid) {
      if (this.tagList.indexOf(Pid) > -1) {
        this.tagList.splice(this.tagList.indexOf(Pid), 1)
      }
      if (this.rightsList.indexOf(Pid) > -1) {
        this.rightsList.splice(this.rightsList.indexOf(Pid), 1)
      }
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 删除权限
      const del = this.allList.filter(v => !keys.includes(v))
      var dellist = []
      for (var j = 0; j < del.length; j++) {
        dellist[j] = { permissionId: del[j], roleId: this.roleId }
      }
      if (dellist.length > 0) {
        axios.post('/rolePer/deletePermission', {
          list: dellist
        })
          .then(() => {
            this.$message.success('成功删除子权限')
          })
          .catch((err) => {
            this.$message.info(err.msg)
          })
      }
    },

    /**
     * @description: 获取角色列表
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    getRolesList() {
      axios.get('/role/getRoles')
        .then((res) => {
          // console.log('role', res)
          this.rolesList = res.data.data
          this.totle = res.data.data.length
        })
        .catch((err) => {
          this.$message.info(err.msg)
        })
    },

    /**
     * @description: 获取权限树
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    getrightsList() {
      axios.get('/rolePer/allPermission')
        .then(res => {
          this.rightsList = res.data.data
          // console.log('res.data', res.data)
          // console.log('this.rightsList', this.rightsList)
          this.getTagList()
        })
        .catch(err => {
          console.error(err)
        })
    },

    /**
     * @description: 分配权限框
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    showSetRightDialog(role) {
      // 获取角色的所有权限
      this.roleId = role
      axios.get(`/rolePer/rolePermission/${role}`)
        .then(res => {
          // console.log('res.data.LeafList', res.data)
          for (var i = 0; i < res.data.LeafList.length; i++) {
            this.defKeys.push(res.data.LeafList[i].permissionId)
          }
          for (var j = 0; j < res.data.AllList.length; j++) {
            this.allList.push(res.data.AllList[j].permissionId)
          }
          this.getrightsList()
        })
        .catch(err => {
          console.error(err)
        })
      //   获取权限树
      this.setRightDialogVisible = true
      this.isShowTree = true
      // console.log('this.defKeys')
      // console.log(this.defKeys)
    },

    /**
     * @description: 分配权限
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    // 分配权限
    allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 增加权限
      const add = keys.filter(v => !this.allList.includes(v))
      var addlist = []
      for (var i = 0; i < add.length; i++) {
        addlist[i] = { permissionId: add[i], roleId: this.roleId }
      }
      if (addlist.length > 0) {
        axios.post('/rolePer/insertPermission', {
          list: addlist
        })
          .then(() => {

          })
          .catch((err) => {
            this.$message.info(err.msg)
          })
      }
      // 删除权限
      const del = this.allList.filter(v => !keys.includes(v))
      var dellist = []
      for (var j = 0; j < del.length; j++) {
        dellist[j] = { permissionId: del[j], roleId: this.roleId }
      }
      if (dellist.length > 0) {
        axios.post('/rolePer/deletePermission', {
          list: dellist
        })
          .then(() => {
            this.$message.success('成功分配权限')
            this.visTree = false
            this.setRightDialogVisible = false
            this.isShowTree = false
          })
          .catch((err) => {
            this.$message.info(err.msg)
          })
      } else {
        this.$message.info('成功分配权限')
        this.visTree = false
        this.setRightDialogVisible = false
        this.isShowTree = false
      }
    },

    /**
     * @description: 关闭分配权限
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    setRightDialogClosed() {
      this.defKeys = []
      this.allList = []
      this.tagList = []
      this.setRightDialogVisible = false
      this.isShowTree = false
      this.f = 0
    },

    /**
     * @description: 添加角色对话框的关闭
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },

    /**
     * @description: 添加角色
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    // 添加角色
    addRoles() {
      axios.post('/role/insert', {
        roleName: this.addRoleForm.roleName
      })
        .then(() => {
          this.$message.success('添加成功')
          this.AddRoleDialogVisible = false
          this.getRolesList()
        })
        .catch(err => {
          console.error(err)
        })
    },

    showEditDialog(role) {
      this.editRoleDialogVisible = true
      this.roleId = role
    },

    /**
     * @description: 编辑角色
     * @param {*}
     * @return {*}
     * @author: Ruohong Yu
     */
    editRoles() {
      axios.post('/role/update', {
        roleId: this.roleId,
        roleName: this.editRoleForm.roleName
      })
        .then(() => {
          this.$message.success('编辑角色成功')
          this.editRoleDialogVisible = false
          this.getRolesList()
        })
        .catch(err => {
          console.error(err)
        })
    },
    editRoleDialogClosed() {
      this.editRoleDialogVisible = false
    },

    /**
     * @description: 删除角色
     * @param {*} role
     * @return {*}
     * @author: Ruohong Yu
     */
    removeRoleById(role) {
      this.deleteRoleDialogVisible = true
      this.roleId = role
    },
    deleteRoles() {
      this.axios.get(`/role/delete/${this.roleId}`)
        .then(() => {
          this.$message.info('删除成功')
          this.deleteRoleDialogVisible = false
          this.getRolesList()
        })
        .catch(err => {
          console.error(err)
        })
    },
    deleteRoleDialogClosed() {
      this.deleteRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tree{
    margin-left: 80px;
  }
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    height: 1px;
    width: 100%;
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
